package be.kuleuven.cs.mop.app.parser;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import be.kuleuven.cs.mop.domain.exceptions.TaskManagerException;
import be.kuleuven.cs.mop.domain.model.impl.Schedule;



/**
 * Utility class for parsing functionality
 */
public class ParserUtils {
	
	@SuppressWarnings("unchecked")
	public static final Element getChild(final Element node, final String child) {
		for (final Element c : (List<Element>)node.getChildren())
			if (c.getName().equalsIgnoreCase(child))
				return c;
		return null;
	}
	
	public static final String getChildText(final Element node, final String child) {
		try {
			return getChild(node, child).getText();
		} catch (final NullPointerException e) {
			//	occurs when getChild(node, child) returns null
		}
		return null;
	}
	
	public static final Calendar getDate(final String date) {
		final Matcher regex =
			Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})")
			.matcher(date);
		if (regex.find()) {
			return new GregorianCalendar(
					Integer.parseInt(regex.group(1)),
					(Integer.parseInt(regex.group(2)) - 1),
					Integer.parseInt(regex.group(3)),
					Integer.parseInt(regex.group(4)),
					Integer.parseInt(regex.group(5)),
					Integer.parseInt(regex.group(6))
			);
		}
		throw new IllegalArgumentException("Invalid 'date & time' syntax");
	}
	
	public static final long getDuration(final String input) {
		return (Long.parseLong(input) * 60000);
	}
	
	@SuppressWarnings("unchecked")
	public static final List<Element> getNodes(final Element parent,
			final String name) {
		for (final Element node : (List<Element>)parent.getChildren())
			if (node.getName().equalsIgnoreCase(name))
				return (List<Element>)node.getChildren();
		
		return new ArrayList<Element>();
	}
	
	public static final Schedule getSchedule(final Element node)
			throws NumberFormatException, TaskManagerException {
		return new Schedule(
				getDate(getChildText(node, "startDate")),
				getDate(getChildText(node, "endDate")),
				getDuration(getChildText(node, "duration"))
		);
	}
	
	public static final Document parse(final File file)
			throws IOException, JDOMException {
		return new SAXBuilder().build(file);
	}
	
}